<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
        <Editor style="height: 400px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed"
            @onFocus="handleFocus" @onBlur="handleBlur" @customAlert="customAlert" @customPaste="customPaste" />
    </div>
</template>



<script setup>
import { addPhoto } from "@/api/user"
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const props = defineProps({
    row: {
        type: String,
        default: '', // 默认值为一个空对象
    },
})
const emit = defineEmits(['closeOK'])
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')
const mode = ref('default')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        const modifiedHtml = props.row
            .replace(
                /<img([^>]*?)data-src="([^"]*?)"([^>]*?)>/gi, '<img$1src="$2"$3>'
            )
            .replace(/<section([^>]*?)>/gi, '')
            .replace(/<\/section>/gi, '')
            .replace(/<p><br\/><\/p>/gi, '<p></p>')
            .replace(/<br\s+\/>/gi, '<br/>')
            .replace(/<p>\s*<\/p>/gi, '')
            .replace(/<p style="display: none;">[\s\S]*?<\/p>/gi, '')

        valueHtml.value = modifiedHtml
        console.log(modifiedHtml);
    }, 500)
    emit('closeOK', valueHtml.value)
})

const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
}
const PathUrl = reactive({
    url: import.meta.env.VITE_APP_API
})
// 图片上传
editorConfig.MENU_CONF['uploadImage'] = {
    async customUpload(file, insertFn) {
        try {
            const formData = new FormData(); // 创建FormData对象用于发送表单数据
            formData.append('file', file);
            axios.post(`${PathUrl.url}/commonUtil/addPhoto`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Authorization': localStorage.getItem('satoken'),
                    'satoken': localStorage.getItem('satoken')
                } // 设置正确的Content-Type头部信息
            }).then(response => {
                insertFn(response.data, 'image', response.data)
            }).catch(error => {
                console.error('Error uploading file:', error); // 上传失败后的处理逻辑
            });
        } catch (error) {
            console.log(error);
        }
    }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor
}
const handleChange = (editor) => {
    emit('closeOK', valueHtml.value)
}
const handleDestroyed = (editor) => {
    // console.log('destroyed', editor)
}
const handleFocus = (editor) => {
    // console.log('focus', editor)
}
const handleBlur = (editor) => {
    emit('closeOK', valueHtml.value)

}
const customAlert = (info, type) => {
    // alert(`【自定义提示】${type} - ${info}`)
}
const customPaste = (editor, event, callback) => {
    // console.log('ClipboardEvent 粘贴事件对象', event)
    // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
    // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
    // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

    // 自定义插入内容
    // editor.insertText(html)

    // 返回 false ，阻止默认粘贴行为
    event.preventDefault()
    // callback(false) // 返回值（注意，vue 事件的返回值，不能用 return）

    // 返回 true ，继续默认的粘贴行为
    callback(true)
}


</script>